<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="付款状态" prop="paymentStatus">
        <el-select
            v-model="queryParams.paymentStatus"
            placeholder="请选择付款状态"
            clearable
            @keyup.enter="handleQuery"
            style="min-width: 200px;">
          <el-option
            v-for="option in paymentStatusOptions"
            :key="option"
            :label="option"
            :value="option"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select
          v-model="queryParams.paymentMethod"
          placeholder="请选择支付方式"
          clearable
          @keyup.enter="handleQuery"
          style="min-width: 200px;">
          <el-option
            v-for="option in paymentMethodOptions"
            :key="option"
            :label="option"
            :value="option"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="orderCreateTime">
        <el-date-picker clearable
          v-model="queryParams.orderCreateTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择订单创建时间"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table 
      v-loading="loading" 
      :data="paymentList" 
      @selection-change="handleSelectionChange"
      style="width: 100%"
      :scroll-x="true">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="订单号" align="center" prop="orderId" min-width="260px"/>
      <el-table-column label="店铺名称" align="center" prop="shopName" min-width="150px" />
      <el-table-column label="支付方式" align="left" prop="paymentMethod" min-width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.paymentMethod === '微信支付'" type="success">微信支付</el-tag>
          <el-tag v-else-if="scope.row.paymentMethod === '支付宝'" type="success">支付宝</el-tag>
          <el-tag v-else type="info">暂未支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="第三方支付流水号" align="center" prop="thirdPartyTransactionId" min-width="260px" />
      <el-table-column label="客户端" align="center" prop="clientSource" min-width="120px" />
      <el-table-column label="支付时间" align="center" prop="paymentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="paymentAmount"  width="120" fixed="right">
        <template #default="scope">
          <span style="color: red; font-weight: bold;">￥{{ formatAmount(scope.row.paymentAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="left" prop="status" width="120" fixed="right">
        <template #default="scope">
          <el-tag v-if="scope.row.paymentStatus === '已支付'" type="success">已支付</el-tag>
          <el-tag v-else type="danger">未支付</el-tag>
        </template>
      </el-table-column>

    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收款记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="paymentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="form.paymentMethod" placeholder="请选择支付方式">
            <el-option
              v-for="option in paymentMethodOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单创建时间" prop="orderCreateTime" >
          <el-date-picker clearable
            v-model="form.orderCreateTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择订单创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付时间" prop="paymentTime">
          <el-date-picker clearable
            v-model="form.paymentTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户端" prop="clientSource">
          <el-input v-model="form.clientSource" placeholder="请输入客户端" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item label="第三方支付流水号" prop="thirdPartyTransactionId">
          <el-input v-model="form.thirdPartyTransactionId" placeholder="请输入第三方支付流水号" />
        </el-form-item>
        <el-form-item label="订单金额" prop="paymentAmount">
          <el-input v-model="form.paymentAmount" placeholder="请输入订单金额" type="number" step="0.01" />
        </el-form-item>
        <el-form-item label="付款状态" prop="paymentStatus">
          <el-select v-model="form.paymentStatus" placeholder="请选择付款状态">
            <el-option
              v-for="option in paymentStatusOptions"
              :key="option"
              :label="option"
              :value="option"
            />
          </el-select>
        </el-form-item>
        <el-divider content-position="center">商品订单信息</el-divider>
        <el-table :data="orderMainList" :row-class-name="rowOrderMainIndex" @selection-change="handleOrderMainSelectionChange" ref="orderMain">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="买家名称" prop="buyerName" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.buyerName" placeholder="请输入买家名称" />
            </template>
          </el-table-column>
          <el-table-column label="订单来源" prop="orderSource" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.orderSource" placeholder="请输入订单来源" />
            </template>
          </el-table-column>
          <el-table-column label="订单类型" prop="orderType" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.orderType" placeholder="请选择订单类型">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" prop="orderAmount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.orderAmount" placeholder="请输入订单金额" />
            </template>
          </el-table-column>
          <el-table-column label="订单状态" prop="orderStatus" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.orderStatus" placeholder="请选择订单状态">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="下单时间" prop="createTime" width="240">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.createTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择下单时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="发票信息" prop="invoiceInfo" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.invoiceInfo" placeholder="请输入发票信息" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Payment">
import { listPayment, getPayment, delPayment, addPayment, updatePayment, getPaymentStatusOptions, getPaymentMethodOptions } from "@/api/orders/payment"

const { proxy } = getCurrentInstance()

const paymentList = ref([])
const orderMainList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedOrderMain = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 选项数据
const paymentStatusOptions = ref([])
const paymentMethodOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    paymentMethod: null,
    orderCreateTime: null,
    paymentStatus: null,
  },
  rules: {
    orderId: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询收款记录列表 */
function getList() {
  loading.value = true
  listPayment(queryParams.value).then(response => {
    paymentList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderId: null,
    paymentMethod: null,
    orderCreateTime: null,
    paymentTime: null,
    paymentAmount: null,
    clientSource: null,
    paymentStatus: null,
    shopName: null,
    thirdPartyTransactionId: null
  }
  orderMainList.value = []
  proxy.resetForm("paymentRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paymentRef"].validate(valid => {
    if (valid) {
      form.value.orderMainList = orderMainList.value
      if (form.value.id != null) {
        updatePayment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPayment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}


/** 商品订单序号 */
function rowOrderMainIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}


/** 复选框选中数据 */
function handleOrderMainSelectionChange(selection) {
  checkedOrderMain.value = selection.map(item => item.index)
}



/** 加载选项数据 */
function loadOptions() {
  // 加载支付状态选项
  getPaymentStatusOptions().then(response => {
    paymentStatusOptions.value = response.data || []
  }).catch(() => {
    paymentStatusOptions.value = []
  })
  
  // 加载支付方式选项
  getPaymentMethodOptions().then(response => {
    paymentMethodOptions.value = response.data || []
  }).catch(() => {
    paymentMethodOptions.value = []
  })
}

/** 格式化金额显示，保留两位小数 */
function formatAmount(amount) {
  if (amount === null || amount === undefined || amount === '' || amount === 0) {
    return '0.00'
  }
  
  // 处理字符串类型的数字
  let num
  if (typeof amount === 'string') {
    num = parseFloat(amount)
  } else if (typeof amount === 'number') {
    num = amount
  } else {
    // 处理可能的对象类型（如BigDecimal序列化后的对象）
    num = parseFloat(String(amount))
  }
  
  if (isNaN(num)) {
    return '0.00'
  }
  
  // 保留两位小数并格式化
  return num.toFixed(2)
}

getList()
loadOptions()
</script>

<style scoped>
/* 确保表格容器可以横向滚动 */
.el-table {
  overflow-x: auto;
}

/* 表格固定列样式优化 */
.el-table .el-table__fixed-right {
  box-shadow: -1px 0 8px rgba(0, 0, 0, 0.12);
}

.el-table .el-table__fixed-left {
  box-shadow: 1px 0 8px rgba(0, 0, 0, 0.12);
}

/* 表格容器最大宽度设置 */
.app-container {
  overflow-x: auto;
}
</style>
